#!/bin/sh

# Override these variables in sourced script(s) located
# in /usr/lib/swupdate/conf.d or /etc/swupdate/conf.d
SWUPDATE_ARGS="-v ${SWUPDATE_EXTRA_ARGS}"
SWUPDATE_WEBSERVER_ARGS=""
SWUPDATE_SURICATTA_ARGS=""
SWUPDATE_SOFTWARE_SELECT=""

check_root() {
	CMDLINE=$(cat /proc/cmdline)
	ROOT=$(echo "$CMDLINE" | awk -F 'root=PARTUUID=' '{print $2}' | awk '{print $1}')
	SYS_A=$(blkid -o value -s PARTUUID /dev/mmcblk0p2)
	SYS_B=$(blkid -o value -s PARTUUID /dev/mmcblk0p3)

	if [ $ROOT = $SYS_A ]; then
		SWUPDATE_SOFTWARE_SELECT="stable,now_A_next_B"
		return 0
	elif [ $ROOT = $SYS_B ]; then
		SWUPDATE_SOFTWARE_SELECT="stable,now_B_next_A"
		return 0
	else
		SWUPDATE_SOFTWARE_SELECT="unknown"
		exit 1
	fi
}

check_root

# source all files from /etc/swupdate/conf.d and /usr/lib/swupdate/conf.d/
# A file found in /etc replaces the same file in /usr
for f in $( (
	test -d /usr/lib/swupdate/conf.d/ && ls -1 /usr/lib/swupdate/conf.d/
	test -d /etc/swupdate/conf.d && ls -1 /etc/swupdate/conf.d
) | sort -u); do
	if [ -f /etc/swupdate/conf.d/$f ]; then
		. /etc/swupdate/conf.d/$f
	else
		. /usr/lib/swupdate/conf.d/$f
	fi
done

#  handle variable escaping in a simmple way. Use exec to forward open filedescriptors from systemd open.
if [ "$SWUPDATE_WEBSERVER_ARGS" != "" -a "$SWUPDATE_SURICATTA_ARGS" != "" ]; then
	exec /usr/bin/swupdate $SWUPDATE_ARGS -w "$SWUPDATE_WEBSERVER_ARGS" -u "$SWUPDATE_SURICATTA_ARGS" -e "$SWUPDATE_SOFTWARE_SELECT"
elif [ "$SWUPDATE_WEBSERVER_ARGS" != "" ]; then
	exec /usr/bin/swupdate $SWUPDATE_ARGS -w "$SWUPDATE_WEBSERVER_ARGS" -e "$SWUPDATE_SOFTWARE_SELECT"
elif [ "$SWUPDATE_SURICATTA_ARGS" != "" ]; then
	exec /usr/bin/swupdate $SWUPDATE_ARGS -u "$SWUPDATE_SURICATTA_ARGS" -e "$SWUPDATE_SOFTWARE_SELECT"
else
	exec /usr/bin/swupdate $SWUPDATE_ARGS -e "$SWUPDATE_SOFTWARE_SELECT"
fi
